﻿using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.ShipApplyCommand;
using WarehouseManagement.Domain.DTO.ShipApply;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;
namespace WarehouseManagement.Application.CommandHandler.ShipApplyCommandHandlers
{
    public class ShowCommandHandlers:IRequestHandler<ShowCommand,PageDTO<ShowShipDTO>>
    {
        private readonly IShipRequestRepository _shipRequest;
        private readonly IShipRequestProRepository _shipRequestPro;

        public ShowCommandHandlers(IShipRequestRepository shipRequest, IShipRequestProRepository shipRequestPro)
        {
            _shipRequest = shipRequest;
            _shipRequestPro = shipRequestPro;
        }

        public async Task<PageDTO<ShowShipDTO>> Handle(ShowCommand request, CancellationToken cancellationToken)
        {
            var apply = (from a in await _shipRequest.GetAll() select a).ToList();
            var pro = (from p in await _shipRequestPro.GetAll() select p).ToList();

            var list = (from a in apply join b in pro on a.SRANumber equals b.SRANumber
                        where a.IsDel == false &&a.ShipType==0 group new 
                        {a ,b} by  new
                        { 
                            a.ShippRequestAppId,
                            a.SaleContractProductId,
                            a.ShipType,
                          
                            a.SRANumber,
                         
                            a.ShipState
                            //,b.ProNum 
                        } into g
                        select new ShowShipDTO
                        {
                         SaleContractProductId = g.Key.SaleContractProductId,
                            ShippRequestAppId = g.Key.ShippRequestAppId,
                            
                            ShipType = g.Key.ShipType,

                            SRANumber = g.Key.SRANumber,

                            ShipState = g.Key.ShipState,
                            ProNum = g.Sum(x => x.b.ProNum)

                        }).ToList();
         

            int totalcount = list.Count();
            int pagecount = (int)Math.Ceiling(totalcount * 1.0 / request.pageSize);


            PageDTO<ShowShipDTO> page = new PageDTO<ShowShipDTO>()
            {
                TotalCount = totalcount,
                PageCount = pagecount,
                list = list.OrderByDescending(x => x.ShippRequestAppId).Skip((request.pageIndex - 1) * request.pageSize).ToList()
            };

            return page;

        }
    }
}
